/**
 * 
 */
package com.jf.cloud.service.sysmanager.common.taglib.html;


import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.jf.cloud.service.sysmanager.constant.TagConstant;

/**
 * 选择列表多选项标签处理类
 * 
 * @author 程伟平 2012-2-2
 */
public class OptionsTag extends AbstractHtmlTag {
	/**
	 * 序列化版本UID
	 */
	private static final long serialVersionUID = 976263100488251462L;

	/**
	 * 选项列表
	 */
	private List<Map<String, Object>> options;

	/**
	 * 选项键
	 */
	private String labelKey;

	/**
	 * 选项值键
	 */
	private String valueKey;

	/**
	 * 获取选项列表
	 * 
	 * @return 选项列表
	 */
	public List<Map<String, Object>> getOptions() {
		return options;
	}

	/**
	 * 设置选项列表
	 * 
	 * @param options 选项列表
	 */
	public void setOptions(List<Map<String, Object>> options) {
		this.options = options;
	}

	/**
	 * 获取选项键
	 * 
	 * @return 选项键
	 */
	public String getLabelKey() {
		return labelKey;
	}

	/**
	 * 设置选项键
	 * 
	 * @param labelKey 选项键
	 */
	public void setLabelKey(String labelKey) {
		this.labelKey = labelKey;
	}

	/**
	 * 获取选项值键
	 * 
	 * @return 选项值键
	 */
	public String getValueKey() {
		return valueKey;
	}

	/**
	 * 设置选项值键
	 * 
	 * @param valueKey 选项值键
	 */
	public void setValueKey(String valueKey) {
		this.valueKey = valueKey;
	}

	@Override
	public int doStartTag() throws JspException {

		JspWriter writer = pageContext.getOut();

		SelectTag selectTag = (SelectTag) getParent();
		// 选择列表标签值
		String value = selectTag.getValue();

		// 选项标签
		StringBuffer sb = new StringBuffer();
		if (options != null && options.size() > 0) {
			for (Map<String, Object> option : options) {
				String val = String.valueOf(option.get(TagConstant.DICT_OPTION_VALUE_KEY));
				if (valueKey != null && valueKey.length() > 0) {
					val = String.valueOf(option.get(valueKey));
				}

				sb.append("<option value=\"");
				sb.append(val);
				sb.append("\"");
				if (value.equals(val)) {
					sb.append(" selected=\"selected\"");
				}
				sb.append(">");
				if (labelKey != null && labelKey.length() > 0) {
					sb.append(option.get(labelKey));
				} else {
					sb.append(option.get(TagConstant.DICT_OPTION_LABEL_KEY));
				}

				sb.append("</option>\n");
			}
		}

		try {
			writer.println(sb.toString());
		} catch (IOException ex) {
			throw new JspException("选择列表多选项标签HTML输出异常！", ex);
		}

		return SKIP_BODY;
	}
}
